package sparrow.common;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class FakeClient {
	
	private String name;
	private String peer_ip;
	private byte[] buffer;
	private DatagramSocket sock;
	private DatagramPacket packet;
	
	public FakeClient(String name, String ip) {
		this.name = name;
		peer_ip = ip;
		try {
			this.buffer = new byte[1024];	// for receive
			this.sock = new DatagramSocket();
			this.packet = new DatagramPacket(buffer, buffer.length);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	public void sendMessage (String msg) {
		buffer = (name + " " + msg).getBytes();
		try {
			packet.setAddress(InetAddress.getByName(peer_ip));
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
		try {
			sock.send(packet);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void sendMetaData (int id, String label, int rgb) {
		String header = "\r " + id + " " + label + " " + rgb; 
		buffer = header.getBytes();
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
		try {
			packet.setAddress(InetAddress.getByName(peer_ip));
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
		try {
			sock.send(packet);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String receiveMessage() {
		try {
			sock.receive(packet);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] buffer = packet.getData();
		return new String(buffer, 0, buffer.length);
	}
	
	public static void main(String[] args) {
		FakeClient c = new FakeClient("vu", "localhost");
		c.sendMessage("hello");
		String msg = c.receiveMessage();
		System.out.println(msg);
	}
}
